<template>
  <gc-dialog
    title="更新用户"
    :dialog-visible="true"
    @cancel="handleCancle"
    @ok="handleConfirm"
  >
    <el-form
      ref="formRef"
      label-position="top"
      :model="form"
      :rules="formRules"
    >
      <el-form-item label="用户名" prop="username">
        <el-input type="text" v-model="form.username"  placeholder="请输入" disabled />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input type="text" v-model="form.nickname" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <GcUploadImage :imageUrl="form.avatar" @get-image="(url: string) => form.avatar = url" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="form.gender">
          <el-radio label="1">男</el-radio>
          <el-radio label="0">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input-number
          step-strictly
          :step="1"
          :min="1"
          v-model="form.age"
          placeholder="请输入" />
      </el-form-item>
      <el-form-item label="职位" prop="job">
        <el-input type="text" v-model="form.job" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input type="textarea" :rows="2" v-model="form.description" placeholder="请输入" />
      </el-form-item>
    </el-form>
  </gc-dialog>
</template>

<script setup lang="ts" name="OperateUserModal">
import { ref, reactive, watch, type PropType } from 'vue'
import { ruleMaxLength } from '@/utils/rules'
import type { FormInstance, FormRules } from 'element-plus'
import { apiUpdateUser } from '@/http/service'
import { ElMessage } from 'element-plus'
import type { User } from '@/http/type'

const props = defineProps({
  userInfo: {
    type: Object as PropType<null | User>,
    default: () => null
  }
})
const emit = defineEmits(['close-modal'])
const formRef = ref<null | FormInstance>(null)
const form = reactive({
  username: '',
  nickname: '',
  gender: null,
  avatar: '',
  age: null,
  job: '',
  description: null
})
const formRules = reactive<FormRules>({
  nickname: [ruleMaxLength(32)],
  description: [ruleMaxLength(255)]
})

/**
 * 用户编辑编辑form表单提交
 */
async function handleConfirm () {
  const valid = await formRef.value?.validate()
  if (valid) {
    await apiUpdateUser(form)
    ElMessage.success('更新用户成功')
    emit('close-modal', true)
  }
}

function handleCancle () {
  emit('close-modal')
}

watch(() => props.userInfo, val => {
  if (!val) return
  const { id, username, nickname, gender, avatar, age, job, description } = val
  Object.assign(form, {
    id, username, nickname, gender, avatar, age, job, description
  })
}, { immediate: true })
</script>

<style scoped lang="scss"></style>
